package com.naiterui.ehp.ps.sms.factory;

/**
 * @Author gaoliangliang
 * @Date 2020/10/20 1:52 下午
 * @Version
 **/

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.K;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.naiterui.ehp.bp.utils.lang.ConfigUtil;
import com.naiterui.ehp.ps.sms.exception.ExceptionCodes;
import com.naiterui.ehp.ps.sms.exception.SmsBusinessException;
import com.naiterui.ehp.ps.sms.utils.constants.SmsConstants;
import com.naiterui.ehp.ps.sms.vo.MessageResponseVO;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class AliyunApi {

    private static final String KEY = ConfigUtil.getString(SmsConstants.API_ALIYUN_KEY);
    private static final String SECRET = ConfigUtil.getString(SmsConstants.API_ALIYUN_SECRET);
    private static final Pattern PATTERN = Pattern.compile("(?=(\\{))[.\\s\\S]*?(?<=(}))");

    /**
     * 单条短信发送
     * @param phone 手机号
     * @param signName 短信签名
     * @param templateCode 模板CODE
     * @param param 参数{"key":"value"}
     */
    public static MessageResponseVO singleSend(String phone, String signName, String templateCode, Map<String, String> param) {
        log.info("发送短信参数：{}, phone {}, signName {}, templateCode {}, key {}, secret {}", param.toString(), phone, signName, templateCode, KEY, SECRET);
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", KEY, SECRET);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", JSON.toJSONString(param));
        MessageResponseVO messageResponseVO = new MessageResponseVO();
        try {
            CommonResponse response = client.getCommonResponse(request);
            log.info("Aliyun Sms Api send result data : {}, httpStatus : {}", response.getData(), response.getHttpStatus());
            messageResponseVO = processApiResult(response.getData());
        } catch (Exception e) {
            log.error("Aliyun Sms Api send ERROR : {}", e.getMessage(), e);
            messageResponseVO.setStatusCode(String.valueOf(ExceptionCodes.HTTP_ERR));
            messageResponseVO.setStatusMsg("服务器繁忙,请稍后再试!");
        }
        return messageResponseVO;
    }

    public static void main(String[] args) {
        System.out.println(buildParamMap("付费问诊，您好!${patient}患者于${time}向您发起了一次付费问诊，本次咨询费${fee}元。请您及时联系患者回复，谢谢！"
        ,new String[]{"患者","时间","咨询费"}));
    }

    /**
     *
     * @param content
     * @param datas
     * @return
     */
    public static Map<String, String> buildParamMap(String content, String[] datas) {

        if (StringUtils.isBlank(content)) {
            return Collections.emptyMap();
        }
        Map<String,String> paramMap = new HashMap<>();
        Matcher m = PATTERN.matcher(content);
        int i = 0;
        while (m.find()) {
            paramMap.put(m.group().substring(1, m.group().length() - 1),datas[i++]);
        }
        return paramMap;
    }

    private static MessageResponseVO processApiResult(String result) throws SmsBusinessException {
        // 处理api请求结果
        if (StringUtils.isBlank(result)) {
            log.error("阿里云平台返回结果为空：[{}]", result);
            throw new SmsBusinessException(ExceptionCodes.SMS_PLATFORM_RETURN_NULL);
        }
        JSONObject resultJson = JSONObject.parseObject(result);
        MessageResponseVO responseVO = new MessageResponseVO();
        String returnStatus = resultJson.getString("Code");
        if ("OK".equals(returnStatus)) {
            responseVO.setStatusCode(String.valueOf(ExceptionCodes.SUCCESS));
            responseVO.setStatusMsg("成功");
        } else {
            responseVO.setStatusCode(String.valueOf(ExceptionCodes.SMS_PLATFORM_RETURN_ERROR));
            responseVO.setStatusMsg(resultJson.getString("Message"));
        }
        return responseVO;
    }
}
